package cn.xzz.findactivityname;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.IShellOutputReceiver;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.find.FindModel;
import com.intellij.find.actions.FindUsagesAction;
import com.intellij.find.findInProject.FindInProjectManager;
import com.intellij.ide.actions.GotoActionBase;
import com.intellij.ide.actions.GotoClassAction;
import com.intellij.ide.actions.GotoSymbolAction;
import com.intellij.ide.actions.runAnything.RunAnythingManager;
import com.intellij.ide.actions.searcheverywhere.ClassSearchEverywhereContributor;
import com.intellij.ide.lightEdit.LightEdit;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.usages.PsiElementUsageTarget;
import com.intellij.usages.UsageTarget;
import com.intellij.usages.UsageView;
import com.intellij.util.ArrayUtil;

import org.jetbrains.android.sdk.AndroidSdkUtils;

import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;

import javax.swing.JOptionPane;

import static com.intellij.find.actions.ShowUsagesAction.startFindUsages;

public class FindCurrentActivity extends AnAction {

    private static final String FIND_ACTIVITY_TITLE = "Current Activity";
    private static final NotificationGroup NOTIFICATION_GROUP =
            NotificationGroup.balloonGroup(FIND_ACTIVITY_TITLE);
    private String activityNameReal;
    private IDevice device;

    @Override
    public void actionPerformed(AnActionEvent e) {

        IDevice[] deviceList = getDeviceList(e.getProject());
        if (deviceList.length == 0) {
            showNotification("device not found!", NotificationType.ERROR);
            return;
        }
        device = deviceList[0];
        if (isADBInstalled()) {
            launchADBFindCurrentActivity(e);
        } else {
            showNotification("adb not found in your environment, please check Android SDK installation and setup, and confirm that adb is available from commandline.", NotificationType.ERROR);
        }
    }

    private void launchADBFindCurrentActivity(AnActionEvent e) {

        String command = "dumpsys window | grep mCurrentFocus";

        getActivityName(e, command);
    }

    private void getActivityName(AnActionEvent e, String command) {
        try {

            device.executeShellCommand(command, new IShellOutputReceiver() {
                @Override
                public void addOutput(byte[] bytes, int i, int i1) {
                    String activityInfo = new String(bytes).trim();
                    String[] split = activityInfo.split(" ");
                    String activityName = split[2].substring(0, split[2].length() - 1);

                    String[] names = activityName.split("/");
                    if (2 == names.length) {
                        if (names[1].startsWith(".")) {
                            activityNameReal = names[0] + names[1];
                        } else {
                            activityNameReal = names[1];
                        }
                        setClipboardString(activityNameReal);

                        int action = JOptionPane.showConfirmDialog(null, activityNameReal + "", FIND_ACTIVITY_TITLE, JOptionPane.DEFAULT_OPTION);
                        new GotoClassAction().actionPerformed(e);

                    } else {
                        showNotification("Activity can't find", NotificationType.ERROR);
                    }
                }

                @Override
                public void flush() {

                }

                @Override
                public boolean isCancelled() {
                    return false;
                }
            });
        } catch (Exception e1) {
            e1.printStackTrace();
            showNotification("", NotificationType.ERROR);
        }
    }

    public static void setClipboardString(String text) {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable trans = new StringSelection(text);
        clipboard.setContents(trans, null);
    }

    public boolean isADBInstalled() {
        return AndroidSdkUtils.isAndroidSdkAvailable();
    }

    public static void showNotification(final String message,
                                        final NotificationType type) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                Notification notification =
                        NOTIFICATION_GROUP.createNotification(FIND_ACTIVITY_TITLE, message, type, null);
                Notifications.Bus.notify(notification);
            }
        });
    }

    private IDevice[] getDeviceList(Project project) {
        AndroidDebugBridge adbFile = AndroidSdkUtils.getDebugBridge(project);
        IDevice[] devices = adbFile != null ? adbFile.getDevices() : new IDevice[0];
        return devices;
    }

}
